#include "stdafx.h"
#include "Lock.h"

namespace Be
{
	Locker::Locker()
		: m_Lock(0)
		, m_ReadLock(0)
	{
	}

	Locker::~Locker()
	{
	}
	
	void Locker::WriteLock()
	{
		while(InterlockedCompareExchange(&m_Lock, 1, 0) != 0)
		{
		}

		while(m_ReadLock)
		{
		}
	}

	void Locker::WriteUnlock()
	{
		InterlockedExchange(&m_Lock, 0);
	}

	void Locker::ReadLock()
	{
		while(InterlockedCompareExchange(&m_Lock, 1, 0) != 0)
		{
		}

		InterlockedIncrement(&m_ReadLock);

		InterlockedExchange(&m_Lock, 0);
	}

	void Locker::ReadUnlock()
	{
		long l_ReadLock = InterlockedDecrement(&m_ReadLock);

		if(l_ReadLock < 0)
		{
			_asm int 3;
		}
	}
}

namespace Be
{
	LockWrite::LockWrite(Locker& p_rLocker)
		: m_rLocker(p_rLocker)
	{
		m_rLocker.WriteLock();
	}

	LockWrite::~LockWrite()
	{
		m_rLocker.WriteUnlock();
	}
}

namespace Be
{
	LockRead::LockRead(Locker& p_rLocker)
		: m_rLocker(p_rLocker)
	{
		m_rLocker.ReadLock();
	}

	LockRead::~LockRead()
	{
		m_rLocker.ReadUnlock();

	}
}